import { ref } from 'vue'

export const useClipboard = () => {
    const clipboardContent = ref(null)

    const executeCopy = async (value_) => {
        if (!askPermission('clipboard-write')) return

        // 兼容性写法
        console.log('copy:', value_, window.isSecureContext);
        if (navigator.clipboard&&window.isSecureContext) {
            var data = [new ClipboardItem({ "text/plain": Promise.resolve(new Blob([JSON.stringify(value_)], { type: "text/plain" })) })];
            clipboardContent.value = value_
            await navigator.clipboard.write(data)
        } else {
            var copyStr;
            if (Object.prototype.toString.call(value_) === "[object Object]"
                || Object.prototype.toString.call(value_) === "[object Array]") {
                copyStr = JSON.stringify(value_)
            } else if (Object.prototype.toString.call(value_)=== "[object String]") {
                copyStr = value_
            }
            var textArea = document.createElement('textarea')
            textArea.value = copyStr
            textArea.style.border = '0';
            textArea.style.padding = '0';
            textArea.style.margin = '0';
            textArea.style.position = "absolute"
            textArea.style.opacity = "0"
            let yPosition = window.innerHeight || document.documentElement.scrollTop;
            textArea.style.left = '-9999px'
            textArea.style.top = `${yPosition}px`
            textArea.setAttribute('readonly', '');
            document.body.appendChild(textArea);
            textArea.focus()
            textArea.select()
            
            try {
                const res = document.execCommand('copy')
                textArea.remove()
                clipboardContent.value = value_
                return res
              } catch (err) {
                return false;
            }
        }
       
    }

    const executeCut = () => {

    }

    const executeBatchCopy = (event, list_) => {
        var copyStr;

        if (Object.prototype.toString.call(list_) === "[object Object]") {
            copyStr = JSON.stringify(list_)
        } else return false

        // 阻止默认的复制行为
        event.preventDefault(); 
        if (event.clipboardData) {
            try {
                event.clipboardData.setData('text/plain', copyStr)
                clipboardContent.value = list_
                return true
              } catch (err) {
                console.log(err);
                return false;
            }
        }
    }

    const executePaste = async () => {
        if (!askPermission('clipboard-read')) return
        if (navigator.clipboard&&navigator.clipboard.read) {
            try {
                await navigator.clipboard
                .read()
                .then(async (clipboardItems) => {
                    for (const clipboard of clipboardItems) {
                        for (const type of clipboard.types) {
                            // 获取文本数据，字符串和对象或者数组类型均可
                            if (type === 'text/plain') {
                                const blob = await clipboard.getType(type);
                                const clipText = await blob.text()
                                const data = JSON.parse(clipText)
                                data&&(clipboardContent.value = data)
                                console.log(data);
                            }
                        }
                        
                    }
                }).catch(err => {
                    console.error("读取剪贴板内容异常: ", err);
                });
            } catch (error) {
                console.error("读取剪贴板内容失败: ", error);
            }
        }
    }

    const setCliboard = () => {
        clipboardContent.value = null
    }

    const executeBathcMove = (moveData_) => {
        clipboardContent.value = moveData_
    }

    // 向用户请求剪贴板读写权限
    const askPermission = async (auth) => {
        try {
            const { state } = await navigator.permissions.query({
                name: auth
            });
            return state === "granted";
        } catch (error) {
            var msg = auth === 'clipboard-read' ? '用户未授权访问剪贴板':'用户未授权写入剪贴板'
            console.log(msg);
            return false;
        }
    }

    return {
        clipboardContent,
        setCliboard,
        executeCopy,
        executeBatchCopy,
        executeBathcMove,
        executeCut,
        executePaste,
    }
}